package cn.edu.njust.epms.common.ExceptionHandler;

import cn.edu.njust.epms.common.Resp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理类（SQL）
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Order(0)
@Slf4j
public class GlobalExceptionHandler {

    /**
     * SQL异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(SQLException.class)
    public Resp<String> exceptionHandler(SQLException e) {
//        System.out.println(e instanceof SQLIntegrityConstraintViolationException);
        if (e instanceof SQLIntegrityConstraintViolationException) {
            log.error(e.getMessage());
//            System.out.println("数据库异常！");
            if (e.getMessage().contains("Duplicate entry")) {
                String[] split = e.getMessage().split(" ");
                String msg = split[2] + "已存在!";
                return Resp.error(msg);
            }
        }
        return Resp.error("数据库错误:"+e.getMessage());
    }
}
